//
//  WSMyViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/10/22.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSMyViewController.h"
#import "WSShopCarViewController.h"
#import "WSLessonTickedViewController.h"
#import "WSIdentifyViewController.h"
#import "WSIssuedViewController.h"
#import "WSOrderDisplayViewController.h"
#import "WSCourseDisplayViewController.h"
#import "ZH_MineSetUpViewController.h"
#import "ZH_MineInfortionViewController.h"
#import "ZH_MineWalletViewController.h"
#import "ZH_MineInvitationViewController.h"
//#import "ZH_MineOrderViewController.h"
#import "WSMyTopHeader.h"
#import "WSMyTableCell.h"

#import "MyService.h"
#import "WSMyGroup.h"
#import "WSMyGroupItem.h"
#import "WSUserInfo.h"

static NSString *CellID = @"WSMyTableCell";

@interface WSMyViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
@property (nonatomic, strong) NSMutableArray <WSMyGroup *> *groups;
@property (nonatomic, strong) WSMyTopHeader *topHeader;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *titleLabel;
// 当前分组 选中item的title
@property (nonatomic, copy) NSString *selectTitle;

@end

@implementation WSMyViewController

#pragma mark - Life Cycle
- (void)dealloc {
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self ws_addSubviews];
    [self ws_setup];
    [self ws_loadData];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.topHeader.xmg_height = self.topHeader.topView.xmg_height + 232.f;
}

#pragma mark - Override
- (void)ws_setup {
    [self setupGroups];
    
    // call backs
    WEAKSELF

    // 我的订单
    /// 查看所有订单
    self.topHeader.checkAllOrderCallback = ^{
        [weakSelf jumpOrderPageAt:0];
    };
    /// 待付款
    self.topHeader.willPayCallback = ^{
        [weakSelf jumpOrderPageAt:1];
    };
    /// 待发货
    self.topHeader.willSendCallback = ^{
        [weakSelf jumpOrderPageAt:2];
    };
    /// 待收货
    self.topHeader.willAcceptCallback = ^{
        [weakSelf jumpOrderPageAt:3];
    };
    /// 已发货
    self.topHeader.didSendCallback = ^{
        [weakSelf jumpOrderPageAt:4];
    };
    /// 退款
    self.topHeader.refundCallback = ^{
        [weakSelf jumpOrderPageAt:4];
    };
    
    // 我的课程
    /// 查看所有
    self.topHeader.checkAllCallback = ^{
        [weakSelf jumpCoursePageAt:0];
    };
    /// 预约课程
    self.topHeader.appointmentCallback = ^{
        [weakSelf jumpCoursePageAt:1];
    };
    /// 线下课程
    self.topHeader.offLineCallback = ^{
        [weakSelf jumpCoursePageAt:2];
    };
    /// 直播课程
    self.topHeader.liveCallback = ^{
        [weakSelf jumpCoursePageAt:3];
    };
    /// 视频课程
    self.topHeader.videoCallback = ^{
        [weakSelf jumpCoursePageAt:4];
    };
    /// 课程订单
    self.topHeader.courseOrderCallback = ^{
        WSCourseDisplayViewController *controller = [[WSCourseDisplayViewController alloc] init];
        controller.isOrder = YES;
        [weakSelf.navigationController pushViewController:controller animated:YES];
    };
}

- (void)ws_addSubviews {
    self.tableView.tableHeaderView = self.topHeader;
    self.tableView.tableFooterView = [UIView new];
    [self.view addSubview:self.tableView];
}

- (void)ws_loadData {
//    dispatch_group_t group = dispatch_group_create();
    // 获取个人信息
    [MyService fetchUserInfoCompletion:^(id  _Nonnull responseObj) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:responseObj];
        if (!response.data) {
            return ;
        }
        WSUserInfo *userinfo = [WSUserInfo yy_modelWithJSON:response.data];
        self.topHeader.userInfo = userinfo;
        // save user data to local
        [TFUserDefault setValue:[userinfo yy_modelToJSONObject] forKey:@"userInfo"];
    }];
}
- (void)setupGroups {
    // 创建第0组模型
    WSMyGroup *group0 = [[WSMyGroup alloc] init];
    // 创建行模型
    WSMyGroupItem *group0Item0 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_gwc") title:@"购物车"];
    WSMyGroupItem *group0Item1 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_ksq") title:@"课时劵"];
    WSMyGroupItem *group0Item2 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_wdqb") title:@"我的钱包"];
    WSMyGroupItem *group0Item3 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_jsrz") title:@"教师认证"];
    WSMyGroupItem *group0Item4 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_yqyj") title:@"邀请有奖"];
    WSMyGroupItem *group0Item5 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_wdjf") title:@"我的积分"];
    
    // 设置跳转控制器
    group0Item0.segueIdentifier = [WSShopCarViewController className];
    group0Item1.segueIdentifier = [WSLessonTickedViewController className];
    group0Item2.targevC = [ZH_MineWalletViewController class];
    group0Item3.segueIdentifier = [WSIdentifyViewController className];
    group0Item4.targevC = [ZH_MineInvitationViewController class];
    group0Item5.segueIdentifier = [WSLessonTickedViewController className];
    
    group0.items = @[group0Item0, group0Item1, group0Item2, group0Item3, group0Item4, group0Item5];
    [self.groups addObject:group0];
    
    // 第1组模型
    WSMyGroup *group1 = [[WSMyGroup alloc] init];
    // 第1组行模型
    WSMyGroupItem *group1Item0 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_aboutus") title:@"关于我们"];
    WSMyGroupItem *group1Item1 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_yjfk") title:@"意见反馈"];
    WSMyGroupItem *group1Item2 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_setup") title:@"设置"];
    WSMyGroupItem *group1Item3 = [WSMyGroupItem itemWithImage:WSImageMake(@"icon_hotline") title:@"客服热线"];
    
    group1Item2.targevC = [ZH_MineSetUpViewController class];
    group1.items = @[group1Item0, group1Item1, group1Item2, group1Item3];
    [self.groups addObject:group1];
}

// 跳转订单页面
- (void)jumpOrderPageAt:(NSInteger)index {
    WSOrderDisplayViewController *orderVc = [[WSOrderDisplayViewController alloc] init];
    orderVc.selectIndex = index;
    [self.navigationController pushViewController:orderVc animated:YES];
}

// 跳转我的课程
- (void)jumpCoursePageAt:(NSInteger)index {
    WSCourseDisplayViewController *courseVc = [[WSCourseDisplayViewController alloc] init];
    courseVc.selectIndex = index;
    [self.navigationController pushViewController:courseVc animated:YES];
}


/// 编辑个人资料
- (IBAction)editInfo:(id)sender {
    ZH_MineInfortionViewController *infoVc = [[ZH_MineInfortionViewController alloc] init];
    [self.navigationController pushViewController:infoVc animated:YES];
}

#pragma mark - Util

// 设置cell 的圆角
- (void)setCornersWithCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // 圆角弧度半径
    CGFloat cornerRadius = 3.f;
    // 设置cell的背景色为透明，如果不设置这个的话，则原来的背景色不会被覆盖
    cell.backgroundColor = UIColor.clearColor;
    
    // 创建一个shapeLayer
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
    // 创建一个可变的图像Path句柄，该路径用于保存绘图信息
    CGMutablePathRef pathRef = CGPathCreateMutable();
    // 获取cell的size
    // 第一个参数,是整个 cell 的 bounds, 第二个参数是距左右两端的距离,第三个参数是距上下两端的距离
    CGRect bounds = CGRectInset(cell.bounds, 0, 0);
    
    // CGRectGetMinY：返回对象顶点坐标
    // CGRectGetMaxY：返回对象底点坐标
    // CGRectGetMinX：返回对象左边缘坐标
    // CGRectGetMaxX：返回对象右边缘坐标
    // CGRectGetMidX: 返回对象中心点的X坐标
    // CGRectGetMidY: 返回对象中心点的Y坐标
    
    // 这里要判断分组列表中的第一行，每组section的第一行，每组section的中间行
    
    // CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
    if (indexPath.row == 0) {
        // 初始起点为cell的左下角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
        // 起始坐标为左下角，设为p，（CGRectGetMinX(bounds), CGRectGetMinY(bounds)）为左上角的点，设为p1(x1,y1)，(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点，设为p2(x2,y2)。然后连接p1和p2为一条直线l1，连接初始点p到p1成一条直线l，则在两条直线相交处绘制弧度为r的圆角。
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 终点坐标为右下角坐标点，把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
        
    } else if (indexPath.row == [self.tableView numberOfRowsInSection:indexPath.section]-1) {
        // 初始起点为cell的左上角坐标
        CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
        CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
        // 添加一条直线，终点坐标为右下角坐标点并放到路径中去
        CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
    } else {
        // 添加cell的rectangle信息到path中（不包括圆角）
        CGPathAddRect(pathRef, nil, bounds);
    }
    // 把已经绘制好的可变图像路径赋值给图层，然后图层根据这图像path进行图像渲染render
    layer.path = pathRef;
    backgroundLayer.path = pathRef;
    // 注意：但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
    CFRelease(pathRef);
    // 按照shape layer的path填充颜色，类似于渲染render
    // layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
    layer.fillColor = [UIColor whiteColor].CGColor;
    
    // view大小与cell一致
    UIView *roundView = [[UIView alloc] initWithFrame:bounds];
    // 添加自定义圆角后的图层到roundView中
    [roundView.layer insertSublayer:layer atIndex:0];
    roundView.backgroundColor = UIColor.clearColor;
    // cell的背景view
    cell.backgroundView = roundView;
    
    // 以上方法存在缺陷当点击cell时还是出现cell方形效果，因此还需要添加以下方法
    // 如果你 cell 已经取消选中状态的话,那以下方法是不需要的.
    //    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
    //    backgroundLayer.fillColor = [UIColor whiteColor].CGColor;
    //    [selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
    //    selectedBackgroundView.backgroundColor = UIColor.clearColor;
    //    cell.selectedBackgroundView = selectedBackgroundView;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.groups[section].items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSMyTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[WSMyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
    }
    cell.accessoryView = [[UIImageView alloc] initWithImage:WSImageMake(@"icon_mygetmore")];
    return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    WSMyTableCell *myCell = (WSMyTableCell *)cell;
    myCell.leftIcon.image = self.groups[indexPath.section].items[indexPath.row].icon;
    myCell.titleLabel.text = self.groups[indexPath.section].items[indexPath.row].title;
    if (indexPath.section == 1) {
        if (indexPath.row == 3) {
            myCell.detailLabel.text = @"021-88888888";
        } else {
            myCell.detailLabel.text = @"";
        }
    }
    [self setCornersWithCell:cell atIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WSMyGroupItem *item = self.groups[indexPath.section].items[indexPath.row];
    self.selectTitle = item.title;
    if (item.segueIdentifier) {
        // 获取要跳转的控制器segue
        NSString *identifier = item.segueIdentifier;
        [self performSegueWithIdentifier:identifier sender:nil];
        
    } else {
        // 获取目标控制器
        UIViewController *controller = [[item.targevC alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.f;
}

#pragma mark - UIScrolViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offSetY = scrollView.contentOffset.y;
    [UIView animateWithDuration:0.25f animations:^{
        self.navigationItem.title = offSetY > self.topHeader.topView.xmg_height ? @"我的" : @"";
    }];
}


#pragma mark - Getters
- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = @"我的";
        _titleLabel.font = WSFontMake(18);
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.hidden = YES;
    }
    return _titleLabel;
}
- (WSMyTopHeader *)topHeader {
    if (_topHeader == nil) {
        _topHeader = [WSMyTopHeader viewFromXib];
        WEAKSELF
        // 发布课程
        _topHeader.publishHandle = ^{
            [weakSelf performSegueWithIdentifier:@"AddCourse" sender:nil];
        };
    }
    return _topHeader;
}
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.xmg_width, self.view.xmg_height-TOPBARHEIGHT-kTabBarHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kCommonBackgroudColor;
        _tableView.separatorColor = kSeparatorColor;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 40.f, 0, 0);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 10.f, 0);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (NSMutableArray *)groups {
    if (_groups == nil) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"AddCourse"]) {
        WSIssuedViewController *targetVc = segue.destinationViewController;
        targetVc.isTeacher = YES;
    }
    if ([segue.identifier isEqualToString:[WSLessonTickedViewController className]]) {
        WSLessonTickedViewController *targetVc = segue.destinationViewController;
        targetVc.title = self.selectTitle;
        if ([self.selectTitle isEqualToString:@"课时券"]) {
            targetVc.pageType = 0;
        } else if ([self.selectTitle isEqualToString:@"我的积分"]) {
            targetVc.pageType = 1;
        }
    }
}

@end
